﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

/// <summary>
/// upLoad 的摘要说明
/// </summary>
public class myUpload
{
    private string rootPath;//保存根目录
    private string fileType;//允许的类型字符串,以|间隔
    private string savePath;//保存的子目录名称。
    private int fileMaxSize;

    private FileUpload fileUpload; 
    public string filePath;//最后的保存路径，包括文件名
    public int fileSize;//文件大小


    public myUpload(FileUpload _fileUpload, string _savePath)
	{

        rootPath = ConfigurationManager.AppSettings["upload_root"];
        fileType = ConfigurationManager.AppSettings["upload_type"];
        fileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["upload_maxsize"]);

        fileUpload = _fileUpload;
        savePath = _savePath;
        uploadFile();
	}
    private void uploadFile()
    {
        String fileExtension = System.IO.Path.GetExtension(fileUpload.FileName).ToLower();
        fileSize=fileUpload.PostedFile.ContentLength / 1024;
        if (fileUpload.HasFile&&fileSize <= fileMaxSize && checkFileType(fileExtension))
        {
            //最后的存档文件路径
            filePath = rootPath + savePath + newFileName() + fileExtension;
            string dir = HttpContext.Current.Server.MapPath(rootPath + savePath);
            //检测文件夹是否存在,不存在则建立
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            fileUpload.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(filePath));

        }
        else
        {
            throw new Exception("文件超过了"+fileMaxSize+"kb，或者文件类型不允许。当前允许类型："+fileType);
        }
    }
    private bool checkFileType(string ftype)
    {
        if (fileType.IndexOf("|" +  ftype + "|") < 0)
            return false;
        else
            return true;
    }
    /// <summary>
    /// 根据生成一个文件名称
    /// </summary>
    /// <returns></returns>
    private string newFileName()
    {
        Random Rnd = new Random();
        int strRnd = Rnd.Next(1, 99);
        string sFileName = DateTime.Now.Year.ToString()+DateTime.Now.Month.ToString()+DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + strRnd.ToString();
        return sFileName;
    }
}
